<template>
    <div class="sampleStorage">
        <div class="header">
            <van-nav-bar title="补样入库" left-arrow @click-left="handleLeft">
            </van-nav-bar>
        </div>
        <div class="list">
            <div class="stepBar_top">
                <StepBarTitle title="商品详单" />
            </div>
            <ListItems :row="info" />
            <div class="product_detail_title--content">

                <div class="product_detail_title-content-info">
                    <div class="product_detail_title-content-info-name">邀约人：</div>
                    <div class="product_detail_title-content-info-content">
                        {{ info.sampleUserName }}
                    </div>
                </div>
                <div class="product_detail_title-content-info">
                    <div class="product_detail_title-content-info-name">入库数量：</div>
                    <div class="product_detail_title-content-info-content">
                        <van-stepper v-model="inStockNum" :min="1" :max="999" integer :before-change="onChange" />
                    </div>
                </div>
                <div class="product_detail_title-content-info">
                    <div class="product_detail_title-content-info-left">
                        <div class="left_title">
                            当前库存：
                            <span style="color: #0094FF;">{{ info.stockAvailable || 0 }}件</span>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div class="conputed_bottom" v-show="buttonsShow">
            <div class="retained">
                <div class="label">拍照留存</div>
                <div class="value">
                    <div v-for="(item, index) in evidenceList" :key="index" class="imgList">
                        <div class="loading_pic" v-if="!item.url">
                            <van-loading type="spinner" size="20" />
                        </div>
                        <van-image v-if="item.url" :src="item.url ? item.url + '?x-oss-process=image/resize,w_300' : ''"
                            @click="enlargeImage(item.url)"></van-image>
                        <van-icon v-if="item.url" name="cross" color="#fff"
                            @click.prevent="deleteImg(evidenceList, index)" />
                    </div>
                    <van-image :src="upload" v-if="evidenceList.length < 5" @click="postImage('evidence', 5)"
                        v-throttle:click></van-image>
                </div>
            </div>
            <div class="conputed_bottom_total">
                <div class="conputed_bottom_left">
                    <van-image :src="ruku"></van-image>
                    共<span class="span">{{ inStockNum || 0 }}</span>件商品入库
                </div>
                <div class="button" @click="warehousingSave">入库</div>
            </div>
        </div>
        <van-overlay :show="overlayShow">
            <van-loading color="#1989fa">加载中...</van-loading>
        </van-overlay>
        <van-dialog v-model:show="dialogShow" title="提示" :showConfirmButton="false">
            <div class="dialog_title">是否对所选商品进行入库？</div>
            <div class="dialog_buttons">
                <div @click="cancel" class="cancel">取消</div>
                <van-button @click="warehousingClick" class="save" v-throttle:click :loading="buttonLoading"
                    loading-text="执行中...">确认</van-button>
            </div>
        </van-dialog>
    </div>
</template>

<script setup lang="ts">
import { computed, ref, onMounted, onUnmounted, watch } from "vue";
import { loginStore } from "@/store/login";
import { storeToRefs } from "pinia";
import { useRoute, useRouter } from "vue-router";
import { getEnvValue } from "@/utils/index";
import { getSupplierAddProductsById } from "@/api/productList/index";
import { batchStorage } from '@/api/productHome/index'
import { showImagePreview, showFailToast, showSuccessToast } from "vant";
import { isPositiveInteger } from '@/utils/validate'
import { handleImageUpdate } from "@/utils/handleImageUpdate";
import StepBarTitle from '@/views/productSelection/components/stepBar/stepBarTitle.vue'
import ListItems from './listItem.vue'
const upload = new URL("@/assets/home/upload.png", import.meta.url).href;
const ruku = new URL("@/assets/productHome/icon_ruku.png", import.meta.url).href;
const route = useRoute();
const router = useRouter();
const store = loginStore();
const { token } = storeToRefs(store);
const buttonLoading = ref(false)
const overlayShow = ref(false)
const loading = ref(false)
const inStockNum = ref(1)

// 留存
const evidenceList = ref<any[]>([]);
const buttonsShow = ref(true)
const defaultPhoneHeight = ref(0) //屏幕默认高度
const nowPhoneHeight = ref(0) //屏幕现在的高度

// 二次确认弹窗
const dialogShow = ref(false)

// 关联库存单 数据留存
const info = computed(() => {
    let info: any = route.query.info
    return JSON.parse(info);
})

onMounted(() => {
    inStockNum.value = Number(info.value.sampleNum)
    defaultPhoneHeight.value = window.innerHeight;
    // 添加事件监听器
    window.addEventListener('resize', handleResize);
})
// 处理窗口大小变化的函数
const handleResize = () => {
    nowPhoneHeight.value = window.innerHeight;
};
// 在组件卸载前移除事件监听器
onUnmounted(() => {
    window.removeEventListener('resize', handleResize);
});
watch(nowPhoneHeight, () => {
    if (defaultPhoneHeight.value != nowPhoneHeight.value) {
        // 当软键盘弹出,改变bottomIsSHow变量然后去控制bottom的显示与隐藏
        buttonsShow.value = false
    } else {
        // 相等代表软键盘收起后,与上同理
        buttonsShow.value = true
    }
})
// 步进器限制 阻止输入负数
const onChange = (value: string): any => {
    return new Promise((resolve) => {
        if (value !== '-') {
            resolve(true);
        }
    });
}

/** 返回区分不同地址 */
const handleLeft = () => {
    router.back();
};
/** 图片放大 */
const enlargeImage = (img: string) => {
    if (img) {
        showImagePreview({
            images: [img],
        });
    }
};
/** 删除 */
const deleteImg = (list: any, index: number) => {
    list.splice(index, 1);
};
/** 入库二次确认 */
const warehousingSave = () => {
    dialogShow.value = true
}
/** 入库二次取消 */
const cancel = () => {
    dialogShow.value = false
}
/** 上传图片 */
const postImage = (name: string, count: number) => {
    (window as any).uni.webView.postMessage({
        data: {
            type: "img",
            count: count,
            name: name,
            url: getEnvValue("VITE_APP_UPLOAD_API") + "/resource/oss/upload",
            header: {
                Authorization: `Bearer ${token.value}`,
                clientid: "e5cd7e4891bf95d1d19206ce24a7b32e",
            },
        },
    });
};

/** uniapp端回传扫码数据 */
(window as any).msgFromUniapp = async (arg) => {
    // 货架
    if (arg.name == 'warehouse') {
        overlayShow.value = true
        try {
            if (isPositiveInteger(arg.productId)) {
                let res = await getSupplierAddProductsById({ productId: arg.productId });;
                res.data.ssociatedInventory = '请选择'
                res.data.productImage = getEnvValue("VITE_APP_PIC_URL") + res.data.productImage.split(',')[0]
                overlayShow.value = false
            } else {
                showFailToast({ message: '该商品不存在' });
                overlayShow.value = false
            }

        } catch (error) {
            overlayShow.value = false
        }
    }
    // 拍照留存
    if (arg.name == 'evidence') {
        const imageLists = {
            evidence: evidenceList.value,
        };
        const maxCounts = {
            evidence: 5,
        };
        const imageList = imageLists[arg.name];
        const maxCount = maxCounts[arg.name];
        handleImageUpdate(imageList, arg, maxCount);
    }
}
/** 入库 */
const warehousingClick = async () => {
    buttonLoading.value = true
    try {
        // 补样入库
        await batchStorage({
            boList: [{
                productId: info.value.productId,
                inStockNum: inStockNum.value,
                id: info.value.id
            }],
            keepImage: getPicByfullPath(evidenceList.value)
        })
        showSuccessToast('补样入库成功')
        buttonLoading.value = false
        loading.value = false
        router.back()
    } catch {
        buttonLoading.value = false
        loading.value = false
    }
}
/**
 * 图片全路径转半路径
 * @param list 
 */
const getPicByfullPath = (list: any[]) => {
    if (list.length > 0) {
        const updatedList = list.map((item: any) => {
            return item.url.split(getEnvValue("VITE_APP_PIC_URL"))[1];
        });
        return updatedList.join(',');
    } else {
        return '';
    }
}
</script>

<style lang="less" scoped>
.sampleStorage {
    width: 100%;
    height: 100vh;
    display: flex;
    flex-flow: column;

    .header {
        background: linear-gradient(#CDECFF 0%, #FFFFFF 70%);
        filter: blur(0px);
        height: 90px;
        padding-top: 44px;
        box-sizing: border-box;
        width: 100%;
        position: fixed;
        z-index: 6003;

        :deep(.van-icon-arrow-left) {
            color: #1a1b1c !important;
        }

        :deep(.van-nav-bar) {
            background: none !important;
        }

        :deep(.van-nav-bar__content) {
            background-color: transparent !important;
        }
    }

    .list {
        flex: 1;
        min-height: 0;
        padding-top: 100px;
        box-sizing: border-box;

        .stepBar_top {
            padding: 0 5px;
        }

        .product_detail_title--content {
            margin-top: -10px;
            background: #fff;
            padding: 10px;
            box-sizing: border-box;

            .product_detail_title-content-info {
                margin-top: 20px;
                display: flex;
                align-items: center;
                justify-content: space-between;

                .product_detail_title-content-info-name {
                    font-weight: 400;
                    font-size: 14px;
                    color: #1a1b1c;
                    line-height: 14px;
                    width: 100px;
                }

                .product_detail_title-content-info-left {
                    flex: 1;
                    min-width: 0;
                    display: flex;
                    align-items: center;
                    font-weight: 400;
                    font-size: 14px;
                    color: #1a1b1c;

                    .left_img {
                        width: 14px;
                        height: 14px;
                        margin-left: 15px;
                    }
                }

                .colors {
                    color: #0094FF !important;
                }

                .product_detail_title-content-info-content {
                    flex: 1;
                    min-width: 0;
                    font-weight: 400;
                    font-size: 14px;
                    color: #b8beca;
                    line-height: 14px;
                    margin-left: auto;
                    display: flex;
                    justify-content: flex-end;
                    word-break: break-all;
                }

                .contents {
                    width: 200px;
                    font-weight: 400;
                    font-size: 14px;
                }

                .buttons {
                    width: 67px;
                    height: 26px;
                    background: #fff;
                    border-radius: 2px;
                    font-weight: 400;
                    font-size: 14px;
                    color: #FC2540;
                    text-align: center;
                    line-height: 26px;
                    border: 1px solid #FC2540;
                }
            }
        }
    }

    .conputed_bottom {
        width: 100%;
        background: #FFFFFF;
        box-shadow: 0px -3px 4px 0px rgba(212, 217, 223, 0.3);
        box-sizing: border-box;
        padding: 0 15px;


        .retained {
            width: 100%;
            border-bottom: 1px solid #ececec;
            display: flex;
            flex-flow: column;
            box-sizing: border-box;
            padding: 10px 0 5px;

            .label {
                width: 100%;
                font-weight: 400;
                font-size: 14px;
                color: #1a1b1c;
                margin-bottom: 10px;
            }

            .value {
                width: 100%;
                display: flex;
                flex-wrap: wrap;

                .imgList {
                    position: relative;
                    margin-right: 5px;

                    .loading_pic {
                        width: 90px;
                        height: 90px;
                        display: flex;
                        align-items: center;
                        justify-content: center;
                    }

                    :deep(.van-icon) {
                        position: absolute;
                        top: 0;
                        z-index: 100;
                        right: 0;
                        font-size: 10px;
                        height: 15px;
                        width: 15px;
                        background-color: #000;
                        border-bottom-left-radius: 16px;
                        display: flex;
                        justify-content: center;
                        align-items: center;
                    }

                    :deep(.van-icon-cross:before) {
                        margin: 0 0 1px 2px;
                    }
                }

                :deep(.van-image__img) {
                    width: 60px;
                    height: 60px;
                }
            }
        }

        .conputed_bottom_total {
            width: 100%;
            display: flex;
            align-items: center;
            justify-content: space-between;
            height: 70px;
        }

        .conputed_bottom_left {
            display: flex;
            align-items: center;

            .van-image {
                width: 40px;
                height: 40px;
                font-weight: 400;
                font-size: 14px;
                color: #1A1B1C;
                margin-right: 10px;

            }

            .span {
                font-weight: 500;
                font-size: 21px;
                color: #0094FF;
            }
        }

        .button {
            width: 120px;
            height: 40px;
            background: #0094FF;
            border-radius: 23px;
            text-align: center;
            line-height: 40px;
            font-weight: 400;
            font-size: 14px;
            color: #FFFFFF;
        }
    }
}

.dialog_title {
    text-align: center;
    margin: 20px;
}

.dialog_buttons {
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: space-between;

    .cancel {
        width: 135px;
        height: 44px;
        border-radius: 23px;
        border: 1px solid #1A1B1C;
        text-align: center;
        line-height: 44px;
    }

    .save {
        width: 135px;
        height: 44px;
        background: #0094FF;
        border-radius: 23px;
        text-align: center;
        line-height: 44px;
        font-weight: 400;
        font-size: 14px;
        color: #FFFFFF;
    }
}

:deep(.van-dialog__content) {
    box-sizing: border-box;
    padding: 20px;
}
</style>